//
//  BaseFlipView.m
//  BaoVn
//
//  Created by Le Anh Tai on 11/6/14.
//  Copyright (c) 2014 Le Anh Tai. All rights reserved.
//

#import "BaseFlipView.h"
#import "Utility.h"
#import "BaseNewsItemView.h"

@implementation BaseFlipView

- (instancetype)init
{
    if (self = [super init])
    {
        //child view
        _detailCurrentView = [self instanceForCurrentSwipeItem];
        _detailCurrentView.delegate = self;
        [self addSubview:_detailCurrentView];
        
        _detailTempView = [self instanceForTempSwipeItem];
        _detailTempView.delegate = self;
        [self addSubview:_detailTempView];
        
        //gesture
        UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureHandler:)];
        panGesture.delegate = self;
        [self addGestureRecognizer:panGesture];
        
        [self moveTempViewInFront:NO];
    }
    
    return self;
}

#pragma mark - For Subclass
- (BaseFlipViewItem *)instanceForTempSwipeItem
{
    return [[BaseFlipViewItem alloc] init];
}

- (BaseFlipViewItem *)instanceForCurrentSwipeItem
{
    return [[BaseFlipViewItem alloc] init];
}

- (id)dataForViewAtIndex:(NSInteger)index
{
    NSLog(@"index: %ld", index);
    
    return nil;
}

- (NSInteger)numberOfItemsForEachFlip
{
    return 4;
}

#pragma mark -
- (CGFloat)anchorTopCenter
{
    return -self.bounds.size.height / 2;
}

- (CGFloat)anchorCenter
{
    return (self.bounds.size.height / 2);
}

- (CGFloat)anchorBottomCenter
{
    return (self.bounds.size.height * 1.5);
}

- (void)moveTempViewInFront:(BOOL)isInFront
{
    if (isInFront)
    {
        [self addSubview:_detailCurrentView];
        [self addSubview:_detailTempView];
    }
    else
    {
        [self addSubview:_detailTempView];
        [self addSubview:_detailCurrentView];
    }
}

- (void)sweepCurrentAndTempView
{
    BaseFlipViewItem *temp = _detailCurrentView;
    _detailCurrentView = _detailTempView;
    _detailTempView = temp;
}

- (void)animationToY:(CGFloat)y velocity:(CGFloat)vel forView:(UIView *)view isFlilpUp:(BOOL)isFlipUp
{
    CGFloat distant = abs(view.center.y - y);
    CGFloat time = [Utility estimateTimeWithDis:distant andVelocity:abs(vel)];
    [UIView animateWithDuration:time animations:^{
        view.center = CGPointMake(view.center.x, y);
    } completion:^(BOOL finished) {

    }];
}

- (void)animationSelfToY:(CGFloat)y velocity:(CGFloat)vel isRemove:(BOOL)isRemove
{
    CGFloat distant = abs(self.center.y - y);
    CGFloat time = [Utility estimateTimeWithDis:distant andVelocity:abs(vel)];
    [UIView animateWithDuration:time animations:^{
        self.center = CGPointMake(self.center.x, y);
    } completion:^(BOOL finished) {
        if (isRemove)
        {
            [self removeFromSuperview];
        }
    }];
}

- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
    
    if (_detailTempView.top > 0)
    {
        [_detailTempView setFrame:RECT(0, frame.size.height, self.width, self.height)];
    }
    else
    {
        [_detailTempView setFrame:RECT(0, _detailTempView.top, self.width, self.height)];
    }
    
    [_detailCurrentView setFrame:RECT(0, _detailCurrentView.top, self.width, self.height)];
}

- (void)hideSubControl:(BOOL)hidden
{
    _detailCurrentView.hidden = hidden;
    _detailTempView.hidden = hidden;
}

#pragma mark - Delegate
- (BOOL)gestureRecognizerShouldBegin:(UIPanGestureRecognizer *)gestureRecognizer
{
    if ([gestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]])
    {
        return YES;
    }
    
    return NO;
}

- (void)didSelectFlipItem:(NSInteger)pageNumber
{
    if ([_delegate respondsToSelector:@selector(flipView:didSelectPage:)])
    {
        [_delegate flipView:self didSelectPage:pageNumber+1];
    }
}

- (void)panGestureHandler:(UIPanGestureRecognizer *)recognizer
{
    CGPoint currentTouchPoint = [recognizer locationInView:self.superview];
    CGFloat curY = currentTouchPoint.y;
    
    if (recognizer.state == UIGestureRecognizerStateBegan)
    {
        _preTouchY = curY;
    }
    else if (recognizer.state == UIGestureRecognizerStateChanged)
    {
        CGFloat dy = curY - _preTouchY;
//        NSLog(@"dy  %0.0f", dy);
        //swipe down
        if (dy > 0)
        {
            if (_movingView == nil)
            {
                if (_selectedIndex == 0)
                {
                    return;
                }
                
                //moving item is currentView
                [self moveTempViewInFront:YES];
                
                _selectedIndex --;
                id preValue = [self dataForViewAtIndex:_selectedIndex];
//                [_detailCurrentView loadDataWithValue:preValue];
//                [_detailCurrentView setFrame:_detailCurrentView.frame];
                [_detailTempView loadDataWithValue:preValue];
                [_detailTempView setFrame:_detailCurrentView.frame];

                
                _detailTempView.ofIndex = _selectedIndex;
                
                _detailTempView.centerY = [self anchorTopCenter];
                
                _anchorTempTop = [self anchorTopCenter];
                _anchorTempBottom = [self anchorCenter];
                _movingView = _detailTempView;
                
                [self didSelectFlipItem:_selectedIndex];
            }
        }
        //swipe up
        else
        {
            if (_movingView == nil)
            {
                //moving item is under left
                [self moveTempViewInFront:NO];
                
                _selectedIndex ++;
                
                id nextValue = [self dataForViewAtIndex:_selectedIndex];
                if (nextValue == nil)
                {
                    _selectedIndex --;
                    return;
                }
                
                [_detailTempView loadDataWithValue:nextValue];
                _detailTempView.frame = _detailTempView.frame;
                _detailTempView.centerY = [self anchorCenter];                
                
                _movingView = _detailCurrentView;
                _anchorTempTop = [self anchorTopCenter];
                _anchorTempBottom = [self anchorCenter];
                
                CGPoint center = CGPointMake(_movingView.center.x, _anchorTempBottom);
                _movingView.center = center;
                
                [self didSelectFlipItem:_selectedIndex];
            }
        }
        
        CGFloat newCenterPosition = _movingView.center.y + dy;
        if (newCenterPosition < _anchorTempTop)
        {
            newCenterPosition = _anchorTempTop;
        }
        else if(newCenterPosition > _anchorTempBottom)
        {
            newCenterPosition = _anchorTempBottom;
        }
        
        CGPoint center = CGPointMake(_movingView.center.x, newCenterPosition);
//        NSLog(@"center:%f;%f",center.x,center.y);
        _movingView.center = center;
        _preTouchY = curY;
    }
    else if (recognizer.state == UIGestureRecognizerStateEnded || recognizer.state == UIGestureRecognizerStateCancelled)
    {
        if (_movingView == nil)
        {
            return;
        }
        
        CGPoint currentVelocityPoint = [recognizer velocityInView:self];
        CGFloat currentVelocityY     = currentVelocityPoint.y;
        //swiping down
        if (currentVelocityY > 0)
        {
            //            NSLog(@"End swipe right");
            [self animationToY:_anchorTempBottom velocity:currentVelocityY forView:_movingView isFlilpUp:NO];
            if ([_movingView isEqual:_detailTempView])
            {
                [self sweepCurrentAndTempView];
            }
            else
            {
                //because not swipe the current view up
                _selectedIndex --;
                [self didSelectFlipItem:_selectedIndex];
            }
        }
        //swiping up
        else
        {
//            NSLog(@"End swipe up");
            [self animationToY:_anchorTempTop velocity:currentVelocityY forView:_movingView isFlilpUp:YES];
            if ([_movingView isEqual:_detailCurrentView])
            {
                [self sweepCurrentAndTempView];
            }
            else
            {
                _selectedIndex ++;
                [self didSelectFlipItem:_selectedIndex];
            }
        }
        
        _movingView = nil;
    }
}

#pragma mark -
- (void)flipViewItem:(BaseFlipViewItem *)view didSelectItem:(BaseNewsItemView *)item withData:(NSDictionary *)data
{
    if ([_delegate respondsToSelector:@selector(flipView:didSelectData:)])
    {
        [_delegate flipView:self didSelectData:data];
    }
}

@end
